from __future__ import print_function

##import list
from cli import CLI
import utils
import string
import logging
from os.path import basename, getsize

class S3CLI(CLI):

    _args = None
    _db = None
    _s3 = None
    _pdriveFiles = None
    _pdriveRoot = None
    _cfg = None
    _objectPrefix = None

    def __init__(self, args, db, cfg, s3):
        self._args = args
        self._db = db
        self._pdriveFiles = self._db.fetchKeyValue("pdrive_files")
        self._pdriveRoot = self._db.fetchKeyValue("pdrive_root")
        self._cfg = cfg
        self._s3 = s3

        self._objectPrefix = self._db.fetchKeyValue("aws_s3_objectPrefix")
        if self._objectPrefix is None:
            self._objectPrefix = ""
        self._objectPrefix = string.strip(self._objectPrefix)

        logging.debug("{} instance init'ed".format(__name__))

    def sync(self):
        numFilesToSync = self._db.countFileToSyncToS3();
        numFilesSynced = self._db.countFileSyncedToS3();
        print("{} file(s) to sync / {} file(s) in sysnc".format(numFilesToSync, numFilesSynced))
        count = 1
        for media in self._db.fetchS3SyncList():
            sha256Hash = media["sha256Hash"]
            localFileName = utils.getFqpnFromMediaObject(self._pdriveFiles, media)
            keyname = "{}{}".format(self._objectPrefix, basename(localFileName))
            sizeOfLocalFile = getsize(localFileName)
            
            with open (localFileName, "r") as fp:
                try:
                    print("({}) Uploading sha256Hash {} to s3 as {}".format("{} / {} {}%".format(count, numFilesToSync, round((float(count) / float(numFilesToSync)) * 100 )), sha256Hash, keyname))
                except:
                    print("Uploading...")
                stats = self._s3.putFile(fp, keyname, sizeOfLocalFile)
                print("")
                if stats["etag"] != stats["md5"]:
                    print("File did not transmit successfully.")
                    print("md5 {} expected, etag {} reported".format(stats["md5"], stats["etag"]))
                    raise SystemExit
                self._db.fileSynced(sha256Hash, stats["etag"])
                count = count + 1
    
    
